version 12
#delim ;
set more off;
capture log close;
capture clear;
capture file close _all;

*log using National_bank_analysis3.txt, text replace;
/***!***!***!***!***!*** [National_bank_analysis3.do ] ***!***!***!***!***!
*
* Project: National Banks 		
* Programmer:  Scott Fulford
*
* Date:    	 8/20/2010
*
* Auditor:      
* Audit Date:   
*
* Purpose:      
* 1) Conduct analysis on 1890 county level data of census and National Banking
* 2) 
* 3)
* Inputs: 
      MI_National_banks
*
* Ouputs: 
*	
*
*
***!***!***!***!***!***!***!***!***!***!***!***!***!***!***!***!***/
/*set trace on;*/
pause on;

set memory 800m;
/***Define Global Directory ****/
	local INDIR "$ROOTDIR/Research/National_Banks/Intermediate";
	local DATADIR "$ROOTDIR/Research/National_Banks/Data";
	local PROGDIR  "$ROOTDIR/Research/National_Banks/Programs";
	local OUTDIR  "$ROOTDIR/Research/National_Banks/Intermediate";
	local GRAPHDIR "$ROOTDIR/Research/National_Banks/Intermediate";
	local TEXDIR "$ROOTDIR/Research/National_Banks/Intermediate/Regression_output";



/**** Min population
Exclude county/years that have population less than
****/
local minpop = 1000;

/*Outreg is having trouble writing to disk, which seems to be an interface problem with
the hard drive being too slow, specify the command to slow it down*/
local thisslow 100;



/*Define program to rename the columns of the e(b) and e(V) vector
so that outreg2 can display them appropriately*/
cap program drop renameout;
prog renameout, eclass;
	args varnames eqnames;
	tempname bmat Vmat;
	matrix `bmat' = e(b);
	matrix `Vmat' = e(V);
	matrix colnames `bmat' = `varnames';
	matrix coleq `bmat' = `eqnames';
	matrix colnames `Vmat' = `varnames';
	matrix coleq `Vmat' = `eqnames';
	matrix rownames `Vmat' = `varnames'; 
	matrix roweq `Vmat' = `eqnames';
	ereturn post  `bmat' `Vmat';
end;
	
/*Load data set with state bank capital stocks*/
import excel "`DATADIR'/State and National Banks.xls", sheet("Capital stock requirements") firstrow;
rename State statename;
sort statename;
tempfile stateCS;
save `stateCS', replace;
	
/***Sample Select ****

Select the sample by loading different files.
allrural selects all rural counties (including southern and western ones)
unionrural selects only "union" rural counties (the base regressions)
***/
foreach sampleselect in  /*unionrural*/ allrural  {;
foreach include25 in 25 /*""*/   {;
/*local sampleselect allrural;*/
/*local sampleselect unionrural;*/

/*Whether to include 1902 information about banks entering under 50*/
/*local include25   ; */
/*local include25 25;*/	
/*******************************/


set seed 263034924; /*Seed generated from 1-500,000,000 by www.random.org from atmospheric noise*/


/*Load previously saved MI file
*/

cd `INDIR';
/****
v0 allows scale effects
v3 does not allow scale effects in population (theta set to 0, no ln_tpop in MLE)
***/	
use MI_National_banks`include25'_`sampleselect'_v0, clear;

rename insample_`sampleselect' insample;
drop eps* eta*;

/*Change units so coefficients show marginal effects of gaining a 50 bank for appropriately
defined population size*/
by gisjoin1890: egen maxbanks50c = max(banks50c);
sum tpop if insample & tpop >1000 & year >=1870 & year <=1900 & capitalstock <=50 & maxbanks50c>0;
local marginal_tpop = 14755 ;/**** Hardcode it in so it is not changing**/




/*Exclude counties with small populations. These are very sensitive to model assumptions*/
replace insample = insample & (tpop > `minpop' & tpop<.);

/*Change units to 100 X
replace ln_tval_pc  = ln_tval_pc*100;
replace ln_manuf_val_pc = ln_manuf_val_pc *100;
replace ln_farmprod_val_pc = ln_farmprod_val_pc *100
*/

mi query;
local replications = `r(M)';


/*Create Means and second moments from draws for use in GMM*/
gen Mopt_capital_pc =0;
gen Mexcess_capital_pc=0;
gen Mopt_capital_pc2 =0;
gen Mexcess_capital_pc2=0;

gen MDopt_capital_pc =0;
gen MDexcess_capital_pc=0;
gen MDopt_capital_pc2 =0;
gen MDexcess_capital_pc2=0;
gen Mopt_exc_pc = 0;
gen MCLopt_capital_pc =0;


gen Me2 =0;
gen Me_ebar2 =0;
gen Me_ebar_lag =0;
gen MDe2=0;
/*Create distances errors*/

gen Mde_debar2=0;
gen Mebar_debar =0;
gen Mide2 =0;
gen Mide_idebar2=0;
gen Mebar_idebar =0;



forvalues xx = 1/`replications' {;
	/*Change the units so an increase of 1 is 
	the equivalent of getting a 50 bank for county with the average pop at margin
	*/
	quietly replace _`xx'_opt_capital_pc = _`xx'_opt_capital_pc*(`marginal_tpop') / 50;
	quietly replace _`xx'_excess_capital_pc = _`xx'_excess_capital_pc*(`marginal_tpop' ) / 50;


	quietly replace Mexcess_capital_pc = Mexcess_capital_pc + _`xx'_excess_capital_pc ;
	quietly replace Mopt_capital_pc = Mopt_capital_pc + _`xx'_opt_capital_pc ;
	quietly replace Mexcess_capital_pc2 = Mexcess_capital_pc2 + _`xx'_excess_capital_pc^2 ;
	quietly replace Mopt_capital_pc2 = Mopt_capital_pc2 + _`xx'_opt_capital_pc^2 ;
	quietly replace Mopt_exc_pc = Mopt_exc_pc + _`xx'_opt_capital_pc*_`xx'_excess_capital_pc ;
	quietly replace MCLopt_capital_pc = MCLopt_capital_pc + _`xx'_opt_capital_pc*L._`xx'_opt_capital_pc ;
	
	/*Create first differences*/
	quietly replace MDexcess_capital_pc = MDexcess_capital_pc + _`xx'_excess_capital_pc - L1._`xx'_excess_capital_pc;
	quietly replace MDopt_capital_pc = MDopt_capital_pc + _`xx'_opt_capital_pc -L1._`xx'_opt_capital_pc ;
	quietly replace MDexcess_capital_pc2 = MDexcess_capital_pc2 + (_`xx'_excess_capital_pc - 	L1._`xx'_excess_capital_pc)^2;
	quietly replace MDopt_capital_pc2 = MDopt_capital_pc2 + (_`xx'_opt_capital_pc - L1._`xx'_opt_capital_pc)^2 ;	
};
foreach var in Mopt_capital_pc Mexcess_capital_pc Mopt_capital_pc2 Mopt_exc_pc Mexcess_capital_pc2 MCLopt_capital_pc
				MDopt_capital_pc MDexcess_capital_pc MDopt_capital_pc2  MDexcess_capital_pc2 {;
	replace `var' = `var'/`replications';
};

/*Create error terms*/
forvalues xx = 1/`replications' {;
	capture drop ebar debar idebar;
	quietly replace Me2 = Me2 + (Mopt_capital_pc - _`xx'_opt_capital_pc)^2 ;
	quietly replace MDe2  = MDe2 + ((Mopt_capital_pc - _`xx'_opt_capital_pc) - (L.Mopt_capital_pc - L._`xx'_opt_capital_pc))^2;
	
	quietly by gisjoin1890: egen ebar = mean(Mopt_capital_pc - _`xx'_opt_capital_pc);
	
	
	quietly replace Me_ebar2 =Me_ebar2 + ((Mopt_capital_pc - _`xx'_opt_capital_pc) -ebar)^2 ;
	quietly replace Me_ebar_lag =Me_ebar_lag + ((Mopt_capital_pc - _`xx'_opt_capital_pc) -ebar)*((L.Mopt_capital_pc - L._`xx'_opt_capital_pc) -ebar);
		/*Errors for distances*/
	quietly by gisjoin1890: egen debar = mean(Mopt_capital_pc*mean_dist_bank - _`xx'_opt_capital_pc*mean_dist_bank);
		quietly replace Mde_debar2 =Mde_debar2 + ((Mopt_capital_pc*mean_dist_bank - _`xx'_opt_capital_pc*mean_dist_bank) -debar)^2 ;
	quietly replace Mebar_debar =Mebar_debar + ((Mopt_capital_pc*mean_dist_bank - _`xx'_opt_capital_pc*mean_dist_bank) -debar)*((Mopt_capital_pc - _`xx'_opt_capital_pc) -ebar);

	 quietly by gisjoin1890: egen idebar = mean(Mopt_capital_pc/mean_dist_bank - _`xx'_opt_capital_pc/mean_dist_bank);
		quietly replace Mide_idebar2 =Mide_idebar2 + ((Mopt_capital_pc/mean_dist_bank - _`xx'_opt_capital_pc/mean_dist_bank) -idebar)^2 ;
	quietly replace Mebar_idebar =Mebar_idebar + ((Mopt_capital_pc/mean_dist_bank - _`xx'_opt_capital_pc/mean_dist_bank) -idebar)*((Mopt_capital_pc - _`xx'_opt_capital_pc) -ebar);
};

foreach var in Me2 MDe2 Me_ebar2 Me_ebar_lag Mde_debar2 Mebar_debar Mide_idebar2 Mebar_idebar {;
	replace `var' = `var'/`replications';
};
/*Replace capital stock with its marginal equivalent*/
replace capitalstock_pc = capitalstock_pc*`marginal_tpop' / 50;


/*Make lags, GMM does not seem to like L. notation*/
gen LMopt_capital_pc = L.Mopt_capital_pc;
gen LMexcess_capital_pc = L.Mexcess_capital_pc;

gen Lcapitalstock_pc = L.capitalstock_pc;
gen LMopt_capital_pc2 = L.Mopt_capital_pc2;
gen Dcapitalstock_pc = D.capitalstock_pc;


/******* Select window size *******/

/**For mean ***/
/*Select which counties are close to cutoff boundary*/
gen Mopt_capital = Mopt_capital_pc*tpop *50 / (`marginal_tpop') ;
gen Mexcess_capital = Mexcess_capital_pc*tpop * 50/(`marginal_tpop') ;


/*Use the divide to enter at 50 that is in sample and either includes
	or does not include the banks that move to 25 after 1900*/
if "`include25'" == "25" {;
	gen bestdivide = bestdivide50_pc*tpop;
}; else {;
	gen bestdivide = bestdivide_pc*tpop;
};

gen inwindow=.;
gen inwindow_temp1 =.;
sort gisjoin1890;

local samplenum = 1;
foreach windowsize in 15 10 5 {;
	replace inwindow = abs(	Mopt_capital-(capitalstock-(50-bestdivide)*banks50c)*(banks50c>0 & banks50c<.)-bestdivide*(banks==0));
	replace inwindow_temp1 =(inwindow<=`windowsize');
	/*Selects only counties which are within range of cuttoff in current period*/
	by gisjoin1890 : egen inwindow_`samplenum' = max(inwindow_temp1);
	replace inwindow_`samplenum' = inwindow_`samplenum';
	local samplenum=`samplenum' +1;
};	

local samplenum=`samplenum' -1; /*Keep number correct after loop*/

/*** Create window for MI **/
quietly mi passive: gen opt_capital = opt_capital_pc * tpop *50 / (`marginal_tpop');
quietly mi passive: gen dist_threshold=. ;
quietly mi passive: replace dist_threshold = abs(opt_capital-(capitalstock-(50-bestdivide)*banks50c)*(banks50c>0 & banks50c<.)-bestdivide*(banks==0)) ;
quietly mi passive: by gisjoin1890: egen inwindow_MI1 =max( (dist_threshold <=15) );
quietly mi passive: by gisjoin1890: egen inwindow_MI2 =max( (dist_threshold <=10) );
quietly mi passive: by gisjoin1890: egen inwindow_MI3 =max( (dist_threshold <=5) );


/**Create sample which excludes counties with a capital stock that is ever greater than 300.
There are not many of these, but some counties grow very quickly and might be 
skewing results
local samplenum=`samplenum' +1; /*Next sample num*/
by gisjoin1890: egen maxcapitalstock = max(capitalstock);
gen inwindow_`samplenum' = inwindow_1*(maxcapitalstock<300); /*Gen new sample which is only for those which never get above some maximum (some counties grow very fast in capital, which may affect gamma_e*/
*/



/*********
Create sample which is only for counties with a 50 bank and no other banks, or no banks, and is in the largest window

****/
/*Uncomment to use*/
local samplenum=`samplenum' +1; /*Next sample num*/
capture drop inwindow_temp1;
gen inwindow_temp1 = (((banks50c>0 & banks50c<.) | (banks==0))& (banks==banks50c) & inwindow_1); 
by gisjoin1890 : egen inwindow_`samplenum' = max(inwindow_temp1); 
drop inwindow_temp1;
quietly mi passive: gen inwindow_temp1 = (((banks50c>0 & banks50c<.) | (banks==0))& (banks==banks50c) & inwindow_MI1); 
quietly mi passive: by gisjoin1890 : egen inwindow_MI`samplenum' = max(inwindow_temp1); 
drop   inwindow_temp1;


/*********
Create sample which includes all counties with either a 50 bank or no bank 
and so does not restrict the sample to a window around transition.
This inwindow will be the last one numerically  
****/
/*Uncomment to use*/
local samplenum=`samplenum' +1; /*Next sample num*/
capture drop inwindow_temp1;
gen inwindow_temp1 = ((banks50c>0 & banks50c<.) | (banks==0)); 
by gisjoin1890 : egen inwindow_`samplenum' = max(inwindow_temp1); 
drop inwindow_temp1;
quietly mi passive: gen inwindow_temp1 = ((banks50c>0 & banks50c<.) | (banks==0)); 
quietly mi passive: by gisjoin1890 : egen inwindow_MI`samplenum' = max(inwindow_temp1); 
drop   inwindow_temp1;


/*
quietly mi passive: gen inwindow_MI4 = inwindow_MI1*(maxcapitalstock<300); /*Gen new sample which is only for those which never get above some maximum (some counties grow very fast in capital, which may affect gamma_e*/
*/

/*Look at distribution of opt capital

drop eta* eps*;
mi convert flong, clear;
gen opt_capital_mi = opt_capital_pc*tpop;
twoway (kdensity opt_capital_mi if year==1870 & gisjoin1890==2700390) (kdensity opt_capital_mi if year==1880 & gisjoin1890==2700390) (kdensity opt_capital_mi if year==1890 & gisjoin1890==2700390) (kdensity opt_capital_mi if year==1900 & gisjoin1890==2700390), name(equal2700390__`sampleselect'`include25');
twoway (kdensity opt_capital_mi if year==1870 & gisjoin1890==2700170) (kdensity opt_capital_mi if year==1880 & gisjoin1890==2700170) (kdensity opt_capital_mi if year==1890 & gisjoin1890==2700170) (kdensity opt_capital_mi if year==1900 & gisjoin1890==2700170), name(equal2700170__`sampleselect'`include25');

twoway (kdensity opt_capital_mi if year==1870 & gisjoin1890==5500110) (kdensity opt_capital_mi if year==1880 & gisjoin1890==5500110) (kdensity opt_capital_mi if year==1890 & gisjoin1890==5500110) (kdensity opt_capital_mi if year==1900 & gisjoin1890==5500110), name(equal5500110__`sampleselect'`include25');
/*
twoway (kdensity opt_capital_mi if year==1870) (kdensity opt_capital_mi if year==1880 ) (kdensity opt_capital_mi if year==1890) (kdensity opt_capital_mi if year==1900 ) if opt_capital_mi <60, name(opt_capital_`sampleselect'`include25') legend(label(1 "1870") label( 2 "1880") label( 3 "1890") label( 4 "1900"));
twoway (kdensity opt_capital_mi if year==1870) (kdensity opt_capital_mi if year==1880 ) (kdensity opt_capital_mi if year==1890) (kdensity opt_capital_mi if year==1900 ) if opt_capital_mi <60 & opt_capital_mi >5, name(opt_capital2_`sampleselect'`include25') legend(label(1 "1870") label( 2 "1880") label( 3 "1890") label( 4 "1900"));*/
pause;
};
};
exit;
*/

/*Change units to make tables easier to read*/
foreach varname in ln_totinc_pc1970 ln_tval_pc ln_manuf_val_pc ln_farmprod_val_pc f_manuf gini_farmsize p_imp_farm  {;
	replace `varname' = `varname'*100;
};


sort gisjoin1890 year; /*Still xtset, but lost sorting in conversion from wide to long*/

tempfile estfile;
save `estfile', replace;

cd `TEXDIR';
local outputfile regs_`sampleselect'`include25';
local resultsfile `outputfile'_results;
capture erase `resultsfile'.ster;


/*keep  gisjoin1890 year statenum insample* ln_tval_pc f_manuf  ln_manuf_val_pc ln_farmprod_val_pc farm_yield  p_imp_farm gini_farmsize ln_numfarms meanfarmsize 
ln_manuf_estb manuf_estb_pc manuf_emp p_manuf_emp manuf_wages ln_area_imp_farm  livestock_val_pc mean_dist_bank
liabilities_pc capitalstock_pc loans_pc  tpop  banks liabilities capitalstock loans banks50c pop_urban1880 *excess_capital_pc *opt_capital_pc bestdivide_pc ln_totinc_pc1970 _mi*;

*/

/********** Create comparison values ********
marginal banks is additional banks per capita of adding a bank to the average county population in 1880*/
sum tpop if year == 1880 & insample;
local meanpop = `r(mean)';

local marginal_banks_pc = 1000/`r(mean)'; /*Rember that banks_pc is banks per 1000 people*/
disp "Marginal banks pc: " `marginal_banks_pc';

sum mean_dist_bank if year == 1880 & insample;
local dmarginal_dist_bank = `r(mean)';
local idmarginal_dist_bank = 1/`r(mean)';


sum loans if year == 1880 & insample;
local totalloans = `r(sum)';
sum banks if year == 1880 & insample;
local marginal_loans_pc = (`totalloans'/`r(sum)')/`meanpop';
disp "Marginal loans pc: " `marginal_loans_pc';

/*Adding a capital 50 bank to a county with the average population*/
local marginal_capitalstock_pc = (50/`meanpop');
disp "Marginal capital stock pc: " `marginal_capitalstock_pc';






/***** Compare to 1970 *******/
/*
capture erase `outputfile'_1970.txt;
capture erase `outputfile'_1970.xml;
	
/*** Exclude states for which cannot include a state fixed effect because they are small, and pretty well banked and
so are not constrained 	
         CONNECTICUT |          8       18.18       18.18
            DELAWARE |          3        6.82       25.00
       MASSACHUSETTS |         14       31.82       56.82
        RHODE ISLAND |          5       11.36       68.18
             VERMONT |         14       31.82      100.00
         District of Columbia
**/

/****Variations : in 1900, in 1870, with ln_tval_pc, without it, with and without State FE **/

foreach thisyear in 1900 1870 {;
foreach includetval in "" ln_tval_pc {;
foreach includestateFE in "YES" "NO" {;
		use `estfile', clear;
		/*Exlcude some states in 1870 since not enough observations for all rural data*/
		if `thisyear' == 1870 {;
				keep if statenum != 380 & statenum != 460; /*North and South Dakota*/
		};
		keep if statenum != 90 & statenum != 100 & statenum != 110 & statenum != 250 & statenum != 440 & statenum != 500 ;
		xi, prefix(_S) i.statenum;
		
		if "`includetval'" == "" {;
			if "`includestateFE'" == "YES" {;
				gmm (ln_totinc_pc - ({gamma_e}-{gamma})*Mopt_capital_pc- {gamma}*capitalstock_pc-{_cons} - {xb: _S*})  if inwindow_1 & insample & year == `thisyear', instruments(1: capitalstock_pc Mopt_capital_pc _S* ) 
				 technique(bfgs);
				
			}; else {;
				gmm (ln_totinc_pc -({gamma_e}-{gamma})*Mopt_capital_pc- {gamma}*capitalstock_pc-{_cons}  )  if inwindow_1 & insample & year == `thisyear', instruments(1: capitalstock_pc Mopt_capital_pc )  
				vce(cluster statenum);
			};
		}; else {;
			if "`includestateFE'" == "YES" {;
				gmm (ln_totinc_pc - {alpha}*`includetval'- ({gamma_e}-{gamma})*Mopt_capital_pc- {gamma}*capitalstock_pc-{_cons} - {xb: _S*} )  if inwindow_1 & insample & year == `thisyear', instruments(1: capitalstock_pc Mopt_capital_pc `includetval' _S* )  
				 technique(bfgs);
				
			}; else {;
				gmm (ln_totinc_pc -{alpha}*`includetval' - ({gamma_e}-{gamma})*Mopt_capital_pc- {gamma}*capitalstock_pc-{_cons}  )  if inwindow_1 & insample & year == `thisyear', instruments(1: capitalstock_pc `includetval' Mopt_capital_pc )
				vce(cluster statenum);
			};			
		};

			
		estimates store regests;
		matrix BB=e(b);
		local ncounties `e(N)';
		local marginaleffect1= BB[1,colnumb(BB,"gamma:_cons")]* `marginal_capitalstock_pc';
		disp "Marginal effect: " `marginaleffect1';
		quietly test _b[gamma:_cons]==0 ;
		local pmarginal1 `r(p)';
		local marginaleffect2= BB[1,colnumb(BB,"gamma_e:_cons")]* `marginal_capitalstock_pc';
		disp "Marginal effect: " `marginaleffect2';
		quietly test _b[gamma_e:_cons] ==0;
		local pmarginal2 `r(p)';
	  /*Do the endogenous and exogenous capital have the same effect?*/
		quietly test _b[gamma_e:_cons] -_b[gamma:_cons] ==0 ;
		local op_eq_exc `r(p)';

		estimates restore regests;
		if "`includetval'" == "" {;
			renameout `"Mopt_capital_pc Mexcess_capital_pc  _cons "' `" "" "" ""  "';
		}; else {;
			renameout `"ln_tval_pc Mopt_capital_pc Mexcess_capital_pc  _cons "' `" "" "" "" ""  "';			
		};
		outreg2 using `outputfile'_1970, 
		/*keep(ln_tval_pc excess_capital_pc  opt_capital_pc   )*/ 
				addstat(Counties, `ncounties',  Excess marg. eff.,`marginaleffect1', p-val excess, `pmarginal1', Opt. marg. eff.,`marginaleffect2', p-val opt., `pmarginal2', p-val opt. = excess, `op_eq_exc') 
				addtext(State FE, `includestateFE', Year, `thisyear')  nocons noni noobs
				excel 
				;
			display "Page Break";
};};};
};}; /*Loop over variation individually*/
exit;
*/

/*** Other possible 1970 variations 	
	mi estimate, post esampvaryok saving(`resultsfile', replace): reg ln_totinc_pc excess_capital_pc  opt_capital_pc if insample & inwindow_1, vce(cluster statenum);

	mi estimate, post esampvaryok saving(`resultsfile', replace): reg ln_totinc_pc i.year#c.excess_capital_pc  i.year#c.opt_capital_pc if insample & inwindow_1, vce(cluster statenum);
	mi estimate, post esampvaryok saving(`resultsfile', replace): reg ln_totinc_pc ln_tval_pc i.year#c.excess_capital_pc  i.year#c.opt_capital_pc if insample & inwindow_1, vce(cluster statenum);


	mi estimate, post esampvaryok saving(`resultsfile', replace): reg ln_totinc_pc ln_tval_pc excess_capital_pc L.excess_capital_pc L2.excess_capital_pc L3.excess_capital_pc  opt_capital_pc L.opt_capital_pc L2.opt_capital_pc L3.opt_capital_pc i.statenum if insample & inwindow_1 & statenum != 90 & statenum != 100 & statenum != 250 & statenum != 440 & statenum != 500 & year == 1900, vce(cluster statenum);
		
	mi estimate (sumeffect: _b[excess_capital_pc] + _b[L.excess_capital_pc] +_b[L2.excess_capital_pc] +_b[L3.excess_capital_pc]) using `resultsfile';
	
	mi estimate (sumeffect: _b[opt_capital_pc] + _b[L.opt_capital_pc] +_b[L2.opt_capital_pc] +_b[L3.opt_capital_pc]) using `resultsfile';

	mi estimate (sumeffect: _b[excess_capital_pc] + _b[L.excess_capital_pc] +_b[L2.excess_capital_pc] +_b[L3.excess_capital_pc]+ _b[opt_capital_pc] + _b[L.opt_capital_pc] +_b[L2.opt_capital_pc] +_b[L3.opt_capital_pc]) using `resultsfile';		
	
	mi estimate (sumeffect: _b[excess_capital_pc] + _b[L.excess_capital_pc] +_b[L2.excess_capital_pc] +_b[L3.excess_capital_pc]- _b[opt_capital_pc] - _b[L.opt_capital_pc] -_b[L2.opt_capital_pc] -_b[L3.opt_capital_pc]) using `resultsfile';
*/			


/********* Compare states where easier and harder to open State bank *********
 
 ******


foreach varname in 
ln_tval_pc  

{;
	capture erase `outputfile'_CS`varname'.xml;
	capture erase `outputfile'_CS`varname'.txt;
		merge  m:1 statename using `stateCS';
		 /*optimal capital that is not zero only
		if there are 50 capital banks*/
		gen SCS_Mexcess_capital_pc = Mexcess_capital_pc*CS_lt50_1895;
		gen SCS_Mopt_capital_pc = Mopt_capital_pc*CS_lt50_1895;
		sort gisjoin1890 year;
		gen D`varname' = D.`varname';

		xtreg `varname' Mexcess_capital_pc c.Mexcess_capital_pc#c.CS_1895#i.year Mopt_capital_pc i.year if insample & inwindow_1, fe vce(cluster statenum);
		local ncounties `e(N_g)';
		local nobs `e(N)';
		outreg2 using `outputfile'_CS`varname', 
			addstat(Observations, `nobs', Counties, `ncounties') 
			addtext(County FE, NO, Year FE, YES) nocons noni noobs
			excel  ctitle("CS FE `thisample'")
			 slow(`thisslow');
	
		reg D`varname' MDexcess_capital_pc c.MDexcess_capital_pc#c.CS_1895#i.year MDopt_capital_pc  i.year if insample & inwindow_1 ,  vce(cluster statenum);
		local nobs `e(N)';
		outreg2 using `outputfile'_CS`varname', 
			addstat(Observations, `nobs', Counties, `ncounties') 
			addtext(County FE, NO, Year FE, YES) nocons noni noobs
			excel  ctitle("CS D `thisample'")
			 slow(`thisslow');
		display "Page Break";


};

};};
*/
		


/********* Different Gammas *********
 Allow effect to be different above and below C^T
 ******

	capture erase `outputfile'_dgamma`varname'.xml;
	capture erase `outputfile'_dgamma`varname'.txt;


foreach varname in 
ln_tval_pc  

{;
		 /*optimal capital that is not zero only
		if there are 50 capital banks*/
		gen D_Mopt_capital_pc = Mopt_capital_pc *(capitalstock_pc>0 & capitalstock_pc<.);
		gen D_Mexcess_capital_pc = Mexcess_capital_pc *(capitalstock_pc>0 & capitalstock_pc<.);
		xtreg `varname' Mexcess_capital_pc D_Mexcess_capital_pc Mopt_capital_pc i.year if insample & inwindow_1, fe vce(cluster statenum);
		xtreg `varname' capitalstock_pc Mopt_capital_pc D_Mopt_capital_pc  i.year if insample & inwindow_1, fe vce(cluster statenum);
		local ncounties `e(N_g)';
		capture drop inregs;
		gen inregs = e(sample);
		/*Create demeaned variables for use in GMM */
		/*
		foreach newmeanvar in `varname' capitalstock_pc Mopt_capital_pc {;
			capture drop MM`newmeanvar' AM`newmeanvar' ;
			tempvar MM`newmeanvar' AM`newmeanvar' ;
			/*Group mean*/
			quietly by gisjoin1890: egen `MM`newmeanvar'' = mean(`newmeanvar') if insample & inwindow_1 & inregs;
			/*Overall mean*/
			quietly egen `AM`newmeanvar'' = mean(`newmeanvar') if insample & inwindow_1 & inregs;
			/*Subract county mean, add in overall mean, so mean of variable remains (and can estimate constants, time effects . . .)*/
			quietly gen A`newmeanvar' = `newmeanvar'- `MM`newmeanvar'' + `AM`newmeanvar'' if inregs;
		}	;
		*/		
		/****** GMM allowing different slopes ***
		gen D_AMopt_capital_pc = AMopt_capital_pc *(capitalstock_pc>0 & capitalstock_pc<.); /*optimal capital that is not zero only
		if there are 50 capital banks*/
		gmm (A`varname' -(
		({gamma_e}-{gamma1})*AMopt_capital_pc+ ({gamma1}+{gamma2})*Acapitalstock_pc - {gamma2}*D_AMopt_capital_pc+{_cons}    + {thetaT: _Iyear_1880-_Iyear_1900}))
		if inwindow_1 & insample, instruments(1: Acapitalstock_pc _Iyear_1880-_Iyear_1900 AMopt_capital_pc  D_AMopt_capital_pc)  vce(cluster gisjoin1890);

		
		gmm (A`varname' -(
		({gamma_e}-{gamma1})*AMopt_capital_pc+ ({gamma1}+{gamma2})*Acapitalstock_pc - {gamma2}*D_AMopt_capital_pc+{_cons}    + {thetaT: _Iyear_1880-_Iyear_1900}))
		(A`varname' -(
		({gamma_e}-{gamma1})*(AMopt_capital_pc+ Me_ebar2/AMopt_capital_pc) + ({gamma1}+{gamma2})*Acapitalstock_pc - {gamma2}*(D_AMopt_capital_pc +(Me_ebar2/AMopt_capital_pc) *(capitalstock_pc>0 & capitalstock_pc<.)) +{_cons}    + {thetaT:}))
		if inwindow_1 & insample, instruments(1: Acapitalstock_pc _Iyear_1880-_Iyear_1900 ) instruments(2: AMopt_capital_pc  D_AMopt_capital_pc, nocons) vce(cluster gisjoin1890);
		
		estimates store regests;
		matrix BB=e(b);
		local nobs `e(N)';
		local marginaleffect= (BB[1,colnumb(BB,"gamma1:_cons")] + BB[1,colnumb(BB,"gamma2:_cons")])* `marginal_capitalstock_pc';
		disp "Marginal effect: " `marginaleffect';
		test _b[gamma1:_cons] + _b[gamma2:_cons]  ==0;
		local pmarginal `r(p)';	
			/*Put output for window size table*/
		/*renameout "Mopt_capital_pc Mexcess_capital_pc _cons" `""" "" """';*/
		
		/*Pull counties from the non-gmm xtreg*/
		outreg2 using `outputfile'_dgamma`varname', 
		/*keep(Mexcess_capital_pc Mopt_capital_pc)  */ 
			addstat(Observations, `nobs', Counties, `ncounties',  Marginal effect,`marginaleffect', p-val marginal $\neq$ 0, `pmarginal') 
			addtext(County FE, YES, Year FE, YES) nocons noni noobs
			excel 
			 slow(`thisslow') ;
		display "Page Break";		
				*/

};

};};
*/


/********* Distance *********
 Check whether distance to existing banks changes effect 
of extra banking ******/



capture erase `outputfile'_dist.xml;
capture erase `outputfile'_dist.txt;
gen db_Mexcess_capital_pc =  Mexcess_capital_pc* mean_dist_bank;
gen db_Mopt_capital_pc =  Mopt_capital_pc* mean_dist_bank;
gen db_capitalstock_pc =  capitalstock_pc* mean_dist_bank;
gen db_Mopt_capital_pc2 =  Mopt_capital_pc2* mean_dist_bank;


gen idb_Mexcess_capital_pc =  Mexcess_capital_pc/ mean_dist_bank;
gen idb_Mopt_capital_pc =  Mopt_capital_pc/ mean_dist_bank;
gen idb_capitalstock_pc = capitalstock_pc/ mean_dist_bank;
gen idb_Mopt_capital_pc2 =  Mopt_capital_pc2/ mean_dist_bank;


foreach varname in 
ln_tval_pc  

ln_manuf_val_pc 

ln_farmprod_val_pc
{;
foreach dfunc in id d {;
		xtreg `varname' capitalstock_pc `dfunc'b_capitalstock_pc Mopt_capital_pc `dfunc'b_Mopt_capital_pc i.year if insample & inwindow_1, fe vce(cluster statenum);
		local ncounties `e(N_g)';
		capture drop inregs;
		gen inregs = e(sample);
		/*Create demeaned variables for use in GMM
		foreach newmeanvar in `varname' `dfunc'b_capitalstock_pc `dfunc'b_Mopt_capital_pc `dfunc'b_Mopt_capital_pc2  capitalstock_pc Mopt_capital_pc Mopt_capital_pc2  {;
			capture drop MM`newmeanvar' AM`newmeanvar' ;
			tempvar MM`newmeanvar' AM`newmeanvar' ;
			/*Group mean*/
			quietly by gisjoin1890: egen `MM`newmeanvar'' = mean(`newmeanvar') if inregs;
			/*Overall mean*/
			quietly egen `AM`newmeanvar'' = mean(`newmeanvar') if inregs;  
			/*Subract county mean, add in overall mean, so mean of variable remains (and can estimate constants, time effects . . .)*/
			quietly gen A`newmeanvar' = `newmeanvar'- `MM`newmeanvar'' + `AM`newmeanvar'' if inregs;
		}	;
		*/
		
		/*
		by gisjoin1890: center ln_tval_pc dbank_capitalstock_pc dbank_Mopt_capital_pc dbank_Mopt_capital_pc2  capitalstock_pc Mopt_capital_pc Mopt_capital_pc2 _Iyear_1880 _Iyear_1890 _Iyear_1900 if (year == 1870 | year ==1880 | year ==1890 | year ==1900), casewise;
		*/
		

		/*
		reg A`varname' Acapitalstock_pc A`dfunc'b_capitalstock_pc AMopt_capital_pc A`dfunc'b_Mopt_capital_pc A_Iyear* if insample & inwindow_1, vce(cluster statenum);
		
		reg c_`varname' c_capitalstock_pc c_`dfunc'b_capitalstock_pc c_Mopt_capital_pc c_`dfunc'b_Mopt_capital_pc c__Iyear* if insample & inwindow_1, vce(cluster statenum);
		
		reg `varname' capitalstock_pc `dfunc'b_capitalstock_pc Mopt_capital_pc `dfunc'b_Mopt_capital_pc i.year i.gisjoin1890 if insample & inwindow_1;
		
		gmm (`varname' -({gamma_e})*Mopt_capital_pc- {gamma}*capitalstock_pc - ({gammad_e})*`dfunc'b_Mopt_capital_pc - {gammad}*`dfunc'b_capitalstock_pc-{_cons}    - {thetaT: _Iyear_1880-_Iyear_1900}) 
		if inwindow_1 & insample, instruments(1: capitalstock_pc `dfunc'b_capitalstock_pc _Iyear_1880-_Iyear_1900 Mopt_capital_pc `dfunc'b_Mopt_capital_pc)  vce(cluster statenum) onestep;
		
		gmm (A`varname' -({gamma_e})*AMopt_capital_pc- {gamma}*Acapitalstock_pc - ({gammad_e})*A`dfunc'b_Mopt_capital_pc - {gammad}*A`dfunc'b_capitalstock_pc-{_cons}    - {thetaT: _Iyear_1880-_Iyear_1900}) 
		if inwindow_1 & insample, instruments(1: Acapitalstock_pc A`dfunc'b_capitalstock_pc _Iyear_1880-_Iyear_1900 AMopt_capital_pc A`dfunc'b_Mopt_capital_pc)  vce(cluster statenum) onestep;
	
		gmm (A`varname' -({gamma_e}-{gamma})*AMopt_capital_pc- {gamma}*Acapitalstock_pc - ({gammad_e}-{gammad})*A`dfunc'b_Mopt_capital_pc - {gammad}*A`dfunc'b_capitalstock_pc-{_cons}    - {thetaT: _Iyear_1880-_Iyear_1900}) 
		if inwindow_1 & insample, instruments(1: Acapitalstock_pc A`dfunc'b_capitalstock_pc _Iyear_1880-_Iyear_1900 AMopt_capital_pc A`dfunc'b_Mopt_capital_pc)  vce(cluster statenum);
		*/
		
		/*GMM on levels of demeaned data
		gmm (A`varname' -({gamma_e}-{gamma})*AMopt_capital_pc- {gamma}*Acapitalstock_pc - ({gammad_e}-{gammad})*A`dfunc'b_Mopt_capital_pc - {gammad}*A`dfunc'b_capitalstock_pc-{_cons}    - {thetaT: _Iyear_1880-_Iyear_1900}) 
		(A`varname' -({gamma_e}-{gamma})*AMopt_capital_pc- {gamma}*Acapitalstock_pc - ({gammad_e}-{gammad})*A`dfunc'b_Mopt_capital_pc - {gammad}*A`dfunc'b_capitalstock_pc-{_cons}    - {thetaT:} - ({gamma_e}-{gamma})*Me_ebar2/AMopt_capital_pc -({gammad_e}-{gammad})*Mebar_`dfunc'ebar/AMopt_capital_pc   )
		(A`varname' -({gamma_e}-{gamma})*AMopt_capital_pc- {gamma}*Acapitalstock_pc - ({gammad_e}-{gammad})*A`dfunc'b_Mopt_capital_pc - {gammad}*A`dfunc'b_capitalstock_pc-{_cons}    - {thetaT: } - ({gammad_e}-{gammad})*M`dfunc'e_`dfunc'ebar2/A`dfunc'b_Mopt_capital_pc -({gamma_e}-{gamma})*Mebar_`dfunc'ebar/A`dfunc'b_Mopt_capital_pc  )
		if inwindow_1 & insample, instruments(1: Acapitalstock_pc A`dfunc'b_capitalstock_pc _Iyear_1880-_Iyear_1900 ) instruments(2: AMopt_capital_pc, nocons) instruments(3: A`dfunc'b_Mopt_capital_pc, nocons) vce(cluster gisjoin1890) ;
		*/
		xtreg `varname'  Mexcess_capital_pc   Mopt_capital_pc `dfunc'b_Mexcess_capital_pc  `dfunc'b_Mopt_capital_pc i.year if insample & inwindow_1, vce(cluster statenum) fe;
		local ncounties `e(N_g)';
		local nobs `e(N)';
		estimates store regests;
		matrix BB=e(b);
		

		
		local marginaleffect= BB[1,colnumb(BB,"Mexcess_capital_pc")] + BB[1,colnumb(BB,"`dfunc'b_Mexcess_capital_pc")]* ``dfunc'marginal_dist_bank';
		disp "Marginal effect: " `marginaleffect';
		test _b[Mexcess_capital_pc]+``dfunc'marginal_dist_bank'*_b[`dfunc'b_Mexcess_capital_pc] ==0;
		local pmarginal `r(p)';	
		
		/*		
		renameout `"Mopt_capital_pc Mexcess_capital_pc  `dfunc'b_opt `dfunc'b_excess _cons theta_1880 theta_1890 theta_1900"' `" "" "" "" "" "" "" "" "" "';
		*/
		/*Pull counties from the non-gmm xtreg*/
		outreg2 using `outputfile'_dist,
			addstat(Observations, `nobs', Counties, `ncounties',  Marginal effect,`marginaleffect', p-val marginal $\neq$ 0, `pmarginal') 
			addtext(County FE, YES, Year FE, YES) nocons noni noobs
			excel 
			 slow(`thisslow') ;
		display "Page Break";		

};};



/*****Do analysis of full variations *****
Each run store its estimates in `outputfile'_variablename which I then 
load into excel. 
*/
local variablestoreg 
ln_tval_pc  


ln_manuf_val_pc 

ln_farmprod_val_pc 

f_manuf 

gini_farmsize 

p_imp_farm 

farm_yield 


/*Other variables:
ln_manuf_estb 

manuf_estb_pc 

manuf_emp 

p_manuf_emp 

manuf_wages 

ln_area_imp_farm  

ln_numfarms 

meanfarmsize

livestock_val_pc */
;



foreach varname in `variablestoreg'  {;
	capture erase `outputfile'_`varname'.txt;
	capture erase `outputfile'_D`varname'.txt;
	capture erase `outputfile'_`varname'.xml;
	capture erase `outputfile'_D`varname'.xml;

};

capture erase `outputfile'_comparison.csv;
file open `outputfile'_comparison using `outputfile'_comparison.csv, write;


local numobscompare ;
local numcountiescompare ;
/*set trace on;
set tracedepth 1;*/
foreach varname in  `variablestoreg'  {;
	/*Clear macros that output comparison cases*/
	local firstlinemarg ;
	local secondlinemarg ;
	foreach thisample in 1 2 5 {;
/*	forvalues thisample = 1/5  {;*/
		
		/************************************************/
		/*LEVELS*/
		use `estfile', clear;
		

		/*OLS on capital stock*/

		xtreg `varname'  capitalstock_pc i.year if insample, fe vce(cluster statenum);
		matrix BB=e(b);
		local ncounties `e(N_g)';
		local nobs `e(N)';
		
		outreg2 using `outputfile'_`varname', 
			keep(capitalstock_pc)   
			addstat(Observations, `nobs', Counties, `ncounties') 
			addtext(County FE, YES, Year FE, YES) nocons noni noobs
			excel  ctitle("C `thisample'")
			 slow(`thisslow');
		display "Page Break";
		
		/*Lags on capital stock
		xtreg `varname'  capitalstock_pc Lcapitalstock_pc i.year if insample, fe vce(cluster statenum);
		matrix BB=e(b);
		local nobs `e(N)';
		local marginaleffect= BB[1,colnumb(BB,"capitalstock_pc")]* `marginal_capitalstock_pc' + BB[1,colnumb(BB,"L.capitalstock_pc")]* `marginal_capitalstock_pc';
		disp "Marginal effect: " `marginaleffect';
		test capitalstock_pc + L.capitalstock_pc==0;
		local pmarginal `r(p)';
		local ncounties `e(N_g)';
		outreg2 using `outputfile'_`varname', 
			keep(capitalstock_pc L.capitalstock_pc)  
			addstat(Observations, `nobs', Counties, `ncounties',  Marginal effect,`marginaleffect', p-val marginal $\neq$ 0, `pmarginal') 
			addtext(County FE, YES, Year FE, YES) nocons noni noobs
			excel  
			;
		display "Page Break";
		*/
		
		/*OLS on mean optimal capital*/
		xtreg `varname'  Mopt_capital_pc Mexcess_capital_pc i.year if insample  & inwindow_`thisample', fe vce(cluster statenum);
		local ncounties `e(N_g)';
		local nobs `e(N)';
		matrix BB=e(b);
		local marginaleffect= BB[1,colnumb(BB,"Mexcess_capital_pc")];
		test Mexcess_capital_pc==0;
		local pmarginal `r(p)';
		local firstlinemarg `firstlinemarg' `marginaleffect', ;
		local secondlinemarg `secondlinemarg' `pmarginal', ; 
		if "`varname'" == "ln_tval_pc" {;
			local numobscompare `numobscompare' `nobs', ;
			local numcountiescompare `numcountiescompare' `ncounties', ;
		};
	
		outreg2 using `outputfile'_`varname', 
			keep(Mexcess_capital_pc Mopt_capital_pc )   
			addstat(Observations, `nobs', Counties, `ncounties') 
			addtext(County FE, YES, Year FE, YES) nocons noni noobs
			excel  ctitle("M `thisample'")
			 slow(`thisslow');
		display "Page Break";
				
		/*Lagged OLS on mean optimal capital*/
		xtreg `varname'  Mopt_capital_pc LMopt_capital_pc  Mexcess_capital_pc  LMexcess_capital_pc  i.year if insample  & inwindow_`thisample', fe vce(cluster statenum);
		local ncounties `e(N_g)';
		local nobs `e(N)';
		matrix BB=e(b);
		local marginaleffect= BB[1,colnumb(BB,"Mexcess_capital_pc")] + BB[1,colnumb(BB,"LMexcess_capital_pc")];
		test Mexcess_capital_pc + LMexcess_capital_pc==0;
		local pmarginal `r(p)';
		local firstlinemarg `firstlinemarg' `marginaleffect', , ;
		local secondlinemarg `secondlinemarg' `pmarginal', , ;/*Second comma produces empty column*/
		if "`varname'" == "ln_tval_pc" {;
			local numobscompare `numobscompare' `nobs', ,;
			local numcountiescompare `numcountiescompare' `ncounties', ,;
		};
		outreg2 using `outputfile'_`varname', 
			keep(Mexcess_capital_pc  LMexcess_capital_pc Mopt_capital_pc LMopt_capital_pc  )  
			addstat(Observations, `nobs', Counties, `ncounties') 
			addtext(County FE, YES, Year FE, YES) nocons noni noobs
			excel  ctitle("LM `thisample'")
			 slow(`thisslow');
		display "Page Break";
		
		
		/*MI on optimal capital*/
		mi estimate, post esampvaryok saving(`resultsfile', replace): xtreg `varname'  opt_capital_pc excess_capital_pc i.year if insample  & inwindow_MI`thisample', fe vce(cluster statenum);
		estimates store regests;
		matrix BB=e(b);
		local nobs `e(N_mi)';
		local ncounties `e(N_g_mi)';
		local marginaleffect= BB[1,colnumb(BB,"excess_capital_pc")];
		quietly mi estimate (sumeffect: _b[excess_capital_pc]) using `resultsfile';
		mi testtransform sumeffect;
		local pmarginal `r(p)';	
		
		local firstlinemarg `firstlinemarg' `marginaleffect', ;
		local secondlinemarg `secondlinemarg' `pmarginal', ; 
		if "`varname'" == "ln_tval_pc" {;
			local numobscompare `numobscompare' `nobs', ;
			local numcountiescompare `numcountiescompare' `ncounties', ;
		};
		estimates restore regests;
		outreg2 using `outputfile'_`varname', 
			keep(excess_capital_pc opt_capital_pc )   
			addstat(Observations, `nobs', Counties, `ncounties') 
			addtext(County FE, YES, Year FE, YES) nocons noni noobs
			excel  ctitle("MI `thisample'")
			 slow(`thisslow');
		display "Page Break";
				
		/*Lagged MI */
		mi estimate, post esampvaryok saving(`resultsfile', replace): xtreg `varname'  opt_capital_pc L.opt_capital_pc  excess_capital_pc  L.excess_capital_pc  i.year if insample  & inwindow_MI`thisample', fe vce(cluster statenum);
		estimates store regests;
		matrix BB=e(b);
		local nobs `e(N_mi)';
		local ncounties `e(N_g_mi)';
		local marginaleffect= BB[1,colnumb(BB,"excess_capital_pc")]+ BB[1,colnumb(BB,"L.excess_capital_pc")];
		quietly mi estimate (sumeffect: _b[excess_capital_pc]+_b[L.excess_capital_pc] ) using `resultsfile';
		mi testtransform sumeffect;
		local pmarginal `r(p)';
		local firstlinemarg `firstlinemarg' `marginaleffect', , ;
		local secondlinemarg `secondlinemarg' `pmarginal', , ;/*Second comma produces empty column*/
		if "`varname'" == "ln_tval_pc" {;
			local numobscompare `numobscompare' `nobs', ,;
			local numcountiescompare `numcountiescompare' `ncounties', ,;
		};
		estimates restore regests;
		outreg2 using `outputfile'_`varname', 
			keep(excess_capital_pc  L.excess_capital_pc opt_capital_pc L.opt_capital_pc  )  
			addstat(Observations, `nobs', Counties, `ncounties') 
			addtext(County FE, YES, Year FE, YES) nocons noni noobs
			excel  ctitle("LMI `thisample'")
			 slow(`thisslow');
		display "Page Break";

		/*************************************************/
		
		/*First Differences*/
		
		/*Difference OLS on capital stock*/
		gen D`varname' = D.`varname';
		/*Get counties by quick fixed effects regression*/
		quietly xtreg D`varname'  MDopt_capital_pc MDexcess_capital_pc i.year if insample  & inwindow_`thisample';
		local ncounties `e(N_g)';
		
		reg D`varname'  Dcapitalstock_pc i.year if insample  ,  vce(cluster statenum);
		matrix BB=e(b);
		local nobs `e(N)';

		disp "Counties: " `ncounties';
		test Dcapitalstock_pc==0;
		local pmarginal `r(p)';
		outreg2 using `outputfile'_D`varname', 
			keep(Dcapitalstock_pc)   
			addstat(Observations, `nobs', Counties, `ncounties') 
			addtext(County FE, NO, Year FE, YES) nocons noni noobs
			excel  ctitle("DC `thisample'")
			 slow(`thisslow');
		display "Page Break";
		
		/*Lags 
		xtreg `varname'  capitalstock_pc Lcapitalstock_pc i.year if insample, fe vce(cluster statenum);
		matrix BB=e(b);
		local nobs `e(N)';
		local marginaleffect= BB[1,colnumb(BB,"capitalstock_pc")]* `marginal_capitalstock_pc' + BB[1,colnumb(BB,"L.capitalstock_pc")]* `marginal_capitalstock_pc';
		disp "Marginal effect: " `marginaleffect';
		test capitalstock_pc + L.capitalstock_pc==0;
		local pmarginal `r(p)';
		local ncounties `e(N_g)';
		outreg2 using `outputfile'_`varname', 
			keep(capitalstock_pc L.capitalstock_pc)  
			addstat(Observations, `nobs', Counties, `ncounties',  Marginal effect,`marginaleffect', p-val marginal $\neq$ 0, `pmarginal') 
			addtext(County FE, NO, Year FE, YES) nocons noni noobs
			excel  
			;
		display "Page Break";
		*/
		
		/*OLS on differences*/
		/*Get counties by quick fixed effects regression*/
		quietly xtreg D`varname'  MDopt_capital_pc MDexcess_capital_pc i.year if insample  & inwindow_`thisample', vce(cluster statenum);
		local ncounties `e(N_g)';
		
		reg D`varname'  MDopt_capital_pc MDexcess_capital_pc i.year if insample  & inwindow_`thisample', vce(cluster statenum);
		local nobs `e(N)';
		outreg2 using `outputfile'_D`varname', 
			keep( MDopt_capital_pc MDexcess_capital_pc)   
			addstat(Observations, `nobs', Counties, `ncounties') 
			addtext(County FE, NO, Year FE, YES) nocons noni noobs
			excel  ctitle("DM `thisample'")
			 slow(`thisslow');
		display "Page Break";
		
		reg D`varname'  MDopt_capital_pc MDexcess_capital_pc i.year if insample  & inwindow_`thisample' & year <=1890, vce(cluster statenum);
		local nobs `e(N)';
		outreg2 using `outputfile'_D`varname', 
			keep( MDopt_capital_pc MDexcess_capital_pc)   
			addstat(Observations, `nobs', Counties, `ncounties') 
			addtext(County FE, NO, Year FE, YES) nocons noni noobs
			excel  ctitle("DM `thisample' 70-90")
			 slow(`thisslow');
		display "Page Break";
		
		/* lags		
		xtreg `varname'  Mopt_capital_pc LMopt_capital_pc  Mexcess_capital_pc  LMexcess_capital_pc  i.year if insample  & inwindow_`thisample', fe vce(cluster statenum);
		matrix BB=e(b);
		local nobs `e(N)';
		local marginaleffect= BB[1,colnumb(BB,"Mexcess_capital_pc")]* `marginal_capitalstock_pc' + BB[1,colnumb(BB,"LMexcess_capital_pc")]* `marginal_capitalstock_pc';
		disp "Marginal effect: " `marginaleffect';
		test Mexcess_capital_pc + LMexcess_capital_pc==0;
		local pmarginal `r(p)';
		local ncounties_lag `e(N_g)';
		outreg2 using `outputfile'_`varname', 
			keep(Mopt_capital_pc LMopt_capital_pc  Mexcess_capital_pc  LMexcess_capital_pc)  
			addstat(Observations, `nobs', Counties, `ncounties_lag',  Marginal effect,`marginaleffect', p-val marginal $\neq$ 0, `pmarginal') 
			addtext(County FE, YES, Year FE, YES) nocons noni noobs
			excel  
			 slow(`thisslow');
		display "Page Break";
		*/
		
		
		/*MI on differences*/
		/*Get counties by quick fixed effects regression*/
		quietly mi estimate, post esampvaryok: xtreg D`varname'  D.opt_capital_pc D.excess_capital_pc i.year if insample  & inwindow_MI`thisample', vce(cluster statenum);
		local ncounties `e(N_g_mi)';
		mi estimate, post esampvaryok: reg D`varname'  D.opt_capital_pc D.excess_capital_pc i.year if insample  & inwindow_MI`thisample', vce(cluster statenum);
		local nobs `e(N_mi)';
		outreg2 using `outputfile'_D`varname', 
			keep( D.opt_capital_pc D.excess_capital_pc)   
			addstat(Observations, `nobs', Counties, `ncounties') 
			addtext(County FE, NO, Year FE, YES) nocons noni noobs
			excel  ctitle("D MI `thisample'")
			 slow(`thisslow');
		display "Page Break";
		
	};
	/*Output comparison cases to a file*/
	file write `outputfile'_comparison "`firstlinemarg'" _n;
	file write `outputfile'_comparison "`secondlinemarg'" _n;
};

/*Output comparison number of obs from ln_tval_pc to a file*/
file write `outputfile'_comparison "`numobscompare'" _n;
file write `outputfile'_comparison "`numcountiescompare'" _n;
file close `outputfile'_comparison;

};
};
log close;
exit;


/***Display table of differences and double differences for 
counties 4-6 and 6 to 8****/
keep if groupa <.; 

quietly {;
foreach varname in tpop f_urban  tval_pc  f_manuf manuf_estb_pc manuf_emp_pc farm_mach_val_pc  gini_farmsize banks banks_pc loans_pc liabilities_pc {;
      display "`varname', " _continue;
      foreach year in 1880 1890 1900 {;
             quietly reg D.`varname' groupa if year == `year';
             quietly lincom groupa +_cons;
             matrix B=e(b);
             matrix V=e(V);
             noisily display  scalar(el(B,1,2)) ", " `r(estimate)' ", " scalar(el(B,1,1))  ", " sqrt(el(V,1,1)) ", "_continue;
         };
      noisily display;

};
foreach year in 1880 1890 1900 {;
  	quietly sum tpop if year == `year' & groupa ==0; 
    noisily display   `r(N)' ", "  _continue;
    quietly sum tpop if year == `year' & groupa ==1; 
    noisily display   `r(N)' ", , "  _continue;
};
noisily display;
};

reg D.banks D.tpop groupa;


use `temp1', clear;
log close;
exit;


sum D.tpop D.f_urban D.banks_pc D.tval_pc  D.f_manuf D.f_urban D.manuf_estb_pc D.manuf_emp_pc D.farm_mach_val_pc  D.gini_farmsize if year ==1880 & groupa==0;
sum D.tpop D.f_urban D.banks_pc D.tval_pc  D.f_manuf D.f_urban D.manuf_estb_pc D.manuf_emp_pc D.farm_mach_val_pc  D.gini_farmsize if year ==1880 & groupa==1;
sum D.tpop D.f_urban D.banks_pc D.tval_pc  D.f_manuf D.f_urban D.manuf_estb_pc D.manuf_emp_pc D.farm_mach_val_pc  D.gini_farmsize if year ==1890 & groupa==0;
sum D.tpop D.f_urban D.banks_pc D.tval_pc  D.f_manuf D.f_urban D.manuf_estb_pc D.manuf_emp_pc D.farm_mach_val_pc  D.gini_farmsize if year ==1890 & groupa==1;



log close; 
exit; 
/***Analysis: Splitting counties into groups with 4 to 6 K and 6 to 8 K***/
sum  tpop1870  banks_pc1870 liabilities_pc1870 capitalstock_pc1870 loans_pc1870
	manuf_estb_pc1870
	manuf_val_pc1870
	farmprod_val_pc1870
	livestock_val_pc1870
	area_imp_farm_pc1870
	farm_mach_val_pc1870  
	gini_farmsize1870 if  city6to8_1880 & pop_urban1880<`urbancuttoff';


sum  tpop1870  banks_pc1870 liabilities_pc1870 capitalstock_pc1870 loans_pc1870
	manuf_estb_pc1870
	manuf_val_pc1870
	farmprod_val_pc1870
	livestock_val_pc1870
	area_imp_farm_pc1870
	farm_mach_val_pc1870  
	gini_farmsize1870 if  city4to6_1880 & pop_urban1880<`urbancuttoff';

gen groupA = "B" if city6to8_1880 ==1;
replace groupA = "A" if city4to6_1880 ==1; /*Note a group is A if it has 4 to 6, regardless if it has a 6 to 8*/
/*label def groupA 10 "A" 20 "B";
label values groupA groupA;
drop if city4to6_1880 & city6to8_1880;*/

tempfile tempA;
save `tempA', replace;
keep if groupA !="" & pop_urban1880<`urbancuttoff';

foreach varname in tpop1870 pop_urban1870 f_urban1870 banks_pc1870 liabilities_pc1870  capitalstock_pc1870 loans_pc1870  manuf_estb_pc1870 livestock_val_pc1870 farmprod_val_pc1870  manuf_val_pc1870 area_imp_farm_pc1870 farm_mach_val_pc1870 manuf_emp_pc1870 gini_farmsize1870 Dbanks1880 Dbanks_pc1880 Dmanuf_estb_pc1880 Dlivestock_val_pc1880 Dfarmprod_val_pc1880  Dmanuf_val_pc1880 Darea_imp_farm_pc1880 Dfarm_mach_val_pc1880 Dmanuf_emp_pc1880 Dgini_farmsize1880
{;
	quietly ttest `varname', by(groupA);
	display "`varname', " `r(mu_1)' ", " `r(mu_2)' ", " `r(mu_1)'-`r(mu_2)' ", " `r(p)';
	display ", " `r(sd_1)' ", " `r(sd_2)' ", " `r(se)';
};

use `tempA', clear;

local outputfile regs1890;
capture erase `outputfile'.txt;

local depvars Dtpop1890 Dtval_pc1890 Df_manuf1890 Df_urban1890 Dmanuf_estb_pc1890 Dmanuf_emp_pc1890 Dmanuf_val_pc1890 Dfarmprod_val_pc1890 Dlivestock_val_pc1890  Dfarm_mach_val_pc1890 Darea_imp_farm_pc1890 Dp_imp_farm1890 Dgini_farmsize1890;
foreach depvarname in  `depvars'
{;
	disp _newline(3)" ******Regressions for `depvarname'  **********";
	reg  `depvarname' Dbanks_pc1890 Dbanks_pc1880 if pop_urban1880 < `urbancuttoff';
	outreg2 using `outputfile';
	estimates store ols_`depvarname';
	ivregress 2sls `depvarname' (Dbanks_pc1890 Dbanks_pc1880=city4to6_1870 city4to6_1880) if pop_urban1880<`urbancuttoff', first;
	estimates store iv1_`depvarname';
	outreg2 using `outputfile';

	ivregress 2sls `depvarname' (Dbanks_pc1880=city4to6_1870 city4to6_1880) if pop_urban1880<`urbancuttoff', first;
	outreg2 using `outputfile';
};


local outputfile regs1880;
capture erase `outputfile'.txt;

foreach depvarname in Dtpop1880 Dtval_pc1880 Df_manuf1880 Df_urban1880 Dmanuf_estb_pc1880 Dmanuf_emp_pc1880 Dmanuf_val_pc1880 Dfarmprod_val_pc1880 Dlivestock_val_pc1880 Dfarm_mach_val_pc1880 Darea_imp_farm_pc1880  Dp_imp_farm1880 Dgini_farmsize1880
{;
	disp _newline(3)" ******Regressions for `depvarname'  **********";
	reg  `depvarname'  Dbanks_pc1880 if pop_urban1880 < `urbancuttoff';
	outreg2 using `outputfile';
	ivregress 2sls `depvarname' (Dbanks_pc1880=city4to6_1880) if pop_urban1880<`urbancuttoff', first;
	outreg2 using `outputfile';
};

log close;
exit;
